import time
from config import REQUEST_FORMAT_CODE
from copy import copy,deepcopy
from functools import wraps
def my_router(code,data={}):
   return {'code':code,'msg':REQUEST_FORMAT_CODE.get(code,407),'data':data}

def item2dict(item, filter=[], choose=[]):
   if isinstance(item, list):
      datas = []
      for i in item:
         datas.append(item2dict(i, filter, choose))
      return datas

   data = deepcopy(item.__dict__)
   data.pop('_sa_instance_state')
   if choose:
      return {k: data.get(k) for k in choose}
   for i in filter:
      data.pop(i)
   return data

def ord_limit(data):
   # 一页的数据数量
   offset = int(data.pop('offset'))
   # 分页
   limit = int(data.pop('limit'))
   if offset:
      # 用户默认跳过0页，直接从第二页开始
      # 第一页展示两个，直接跳过？？？
      offset -= 1
      # 用户想看的页数市用户的页数*每页展示的数据
      offset = offset * limit
   return offset,limit

ret_data = {}
ret_time = {}
def my_cache(timeout=60):
   def warp(f):
      @wraps(f)
      def inner(*args,**kwargs):
         function_name = f.__name__
         global ret_data
         new_t = time.time()
         if function_name in ret_time and new_t > ret_time[function_name]:
            ret = f(*args,**kwargs)
            ret_data[function_name] = ret
            ret_time[function_name] =new_t + timeout
            return ret
         elif function_name in ret_data:
            return ret_data[function_name]
         ret = f(*args,**kwargs)
         ret_data[function_name] = ret
         ret_time[function_name] - new_t + timeout
         return ret
      return inner
   return warp
